var app = getApp();
var left_height;//左侧滚动高度
var coll_right_h; //收藏滚动高度
var mySuperShop;
var z_scroH;
var my_options;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    Capsule:app.globalData.Capsule,
    Capsulehei:app.globalData.Capsulehei,
    CustomBar:app.globalData.CustomBar,
    gun:false, //scroll-view是否可以滚动
    is_coop_step:0, //扫码，分享进入，与当前供应商的合作情况（0初始，1可以申请，2申请中可取消，3与当前供应商有合作关系，但是合作关系被暂停了，4不能合作，因下单端使用了总部目录,门店目录，或虽然是供应商目录，但绑定的企业不包含该供应商）,5正常合作
    isAddsuper:false,  //合作窗
    isPower:false, //授权窗
    is_hezuo_showToast:false, //中心提示窗
    isShowHzStep:false //与合作注册的组合显隐值
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let that = this;
    setTimeout(function() {
      const query = wx.createSelectorQuery();
        query.select('.gouwuche_pos').boundingClientRect();
        query.select('.right_top_pos_in').boundingClientRect();
        query.exec((res) => {
        left_height=res[0].top-res[1].top;//左侧滚动高度
        coll_right_h=res[0].bottom-res[1].bottom;
        my_options=options;
        that.setData({
          step:options.step,
          type:options.type, //是否由扫码，分享进入 ‘sao’
          super_info:JSON.parse(options.super_info),
          id:options.id,
          isShowSuperList:1,
          loginInfo:app.globalData.loginInfo,
          left_height:left_height,
          coll_right_h:coll_right_h
        });
        z_scroH=0.2*wx.getSystemInfoSync().windowHeight-app.globalData.Capsule-app.globalData.Capsulehei;
        mySuperShop=that.selectComponent('#mySuperShop');
        if(options.type=='sao'){
          that.judge_coop();
        }else{
          that.setData({
            is_coop_step:5
          });
          mySuperShop.open_onload(options,left_height,coll_right_h,z_scroH);
        };
    });
    }, 200);
  },
  // 关闭授权窗
  closePower(){
    this.setData({
      isShowHzStep:false
    });
  },
  // 微信授权
  getUserProfile:function(e){
    wx.showLoading({
      title: '加载中...',
    });
    wx.getUserProfile({
      desc: '用于完善会员资料', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res);
        var userInfo=res.userInfo;
        var that = this;
        wx.login({
          success: function (ress) {
            console.log(userInfo);
            var data = {
              appId: app.globalData.appId,
              secret: app.globalData.secret,
              code: ress.code,
              head_portrait: userInfo.avatarUrl,
              avatarUrl: userInfo.avatarUrl,
              sex: userInfo.gender,
              country: userInfo.country,
              nickname: userInfo.nickName,
              dk_type:0,
            };
            app.AppHttp('api/Client/ClientPersonalAuth', data, function (res) {
              if (res.data.status == 1) {
                wx.showToast({
                  title: res.data.msg,
                  success: function () {
                    app.globalData.step=1;
                    that.setData({
                      step:1
                    });
                    setTimeout(function () {
                      wx.hideLoading();
                      if(app.globalData.unionid==undefined){ 
                        // 已经授权，可以直接调用 getUserInfo 获取头像昵称，不会弹框
                        wx.getUserInfo({
                          success: res => {
                            // 可以将 res 发送给后台解码出 unionId
                            encryptedData=res.encryptedData;
                            iv=res.iv;
                            app.globalData.userInfo = res.userInfo
                            // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                            // 所以此处加入 callback 以防止这种情况
                            var sdata = {
                              appId: app.globalData.appId,
                              sessionKey:app.globalData.session_key,
                              encryptedData:encryptedData,
                              iv:iv
                            };
                            app.AppHttp('api/Client/DataDecryption',sdata, function (res) {
                                app.globalData.unionid = res.data.unionId;
                                app.AppHttp('api/Client/updateUnionid',{openid:app.globalData.openid,unionid:res.data.unionId}, function (res) {
                                });           
                            });
                          }
                        });
                      };
                    })
                  }
                }, 500);
              } else {
                wx.hideLoading();
                wx.showModal({
                  title: '授权异常'
                });
              }
            });
          }
        });
      }
    });
  },
  // 获取手机号
  getPhoneNumber:function(e){
    var that = this;
    if(e.detail.errMsg == "getPhoneNumber:ok"){  //用户点击了允许
      var iscj=e.currentTarget.dataset.iscj;
      wx.login({
        success:function(res){
          console.log(res);
          var data = {
            appId: app.globalData.appId,
            sessionKey:app.globalData.session_key,
            encryptedData:e.detail.encryptedData,
            iv:e.detail.iv
          };
          app.AppHttp('api/Client/DataDecryption',data, function (res) {
            console.log(JSON.stringify(res.data));
            if(app.globalData.unionid==undefined){   //没有unionId，更新unionId
              app.globalData.unionid = res.data.unionId;
              app.AppHttp('api/Client/updateUnionid',{openid:app.globalData.openid,unionid:res.data.unionId}, function (res) {
                console.log(JSON.stringify(res.data));  
              });
            };
            if(iscj=='cj'){  //创建新门店
              that.bind_and_cre(res.data.phoneNumber,'create');
            }else if(iscj=='add'){  //加入已有门店(仅绑定手机);
              that.bind_and_cre(res.data.phoneNumber,'join');
            };      
          });
        }
      })
    }else{
      console.log('已经拒绝');
    };
  },
  // 绑定手机并创建新门店(或仅绑定手机)
  bind_and_cre:function(phone){
    var that = this;
    app.AppHttp('api/Client/WechatUserBindSupplier',{openid:app.globalData.openid,phone:phone,join_type:'join'}, function (res) {
      console.log(JSON.stringify(res.data));
      wx.showToast({
        title: res.data.msg
      });
      app.globalData.step=2;
      that.setData({
        step:2,
      });
      that.toCreateSuper();
    });
  },
  // 去创建门店
  toCreateSuper:function(){
    wx.navigateTo({   
      url:'/group_space/pages/CreateSuper/CreateSuper?type='+'apply'+'&id='+this.data.id
    });
  },
  // 判断合作情况
  judge_coop(type){
    let that = this;
    if(that.data.step<3){
      that.setData({
        isPower:true,
        is_hezuo_showToast:type=='hezuo_show'?true:false
      });
      mySuperShop.open_onload(my_options,left_height,coll_right_h,z_scroH);
      return;
    }else if(app.globalData.loginInfo.good_dir_set>=2){
      that.setData({
        is_coop_step:4,
        isAddsuper:true,
        is_hezuo_showToast:type=='hezuo_show'?true:false
      });
      mySuperShop.open_onload(my_options,left_height,coll_right_h,z_scroH);
      return;
    };
    app.AppHttp('api/Client/supperDetail', {  
      openid: app.globalData.openid,
      id: that.data.id
    }, function (res) {
      console.log(JSON.stringify(res.data));
      let status = res.data.data.status;
      let copper_id = res.data.data.copper_id;
      that.setData({
        sao_super:res.data.data
      });
      if(that.data.loginInfo.good_dir_set==1){ //供应商目录档口
        if(status==1){
          that.setData({
            is_coop_step:5,
            isAddsuper:false,
            isShowHzStep:false
          });
        }else if(copper_id>0 && status==0){
          that.setData({
            is_coop_step:3,
            isAddsuper:true,
            is_hezuo_showToast:type=='hezuo_show'?true:false
          });
        }else{
          that.setData({
            is_coop_step:4,
            isAddsuper:true,
            is_hezuo_showToast:type=='hezuo_show'?true:false
          });
        };
      }else{  //普通客户
        if(status==1){
          that.setData({
            is_coop_step:5,
            isAddsuper:false,
            isShowHzStep:false
          });
        }else if(copper_id>0 && status==0){
          that.setData({
            is_coop_step:3,
            isAddsuper:true,
            is_hezuo_showToast:type=='hezuo_show'?true:false
          });
        }else{
          if(status==-1){
            that.setData({
              is_coop_step:2,
              isAddsuper:true,
              is_hezuo_showToast:type=='hezuo_show'?true:false
            });
          }else{
            that.setData({
              is_coop_step:1,
              isAddsuper:true,
              is_hezuo_showToast:type=='hezuo_show'?true:false
            });
          }
        };
      };
      mySuperShop.open_onload(my_options,left_height,coll_right_h,z_scroH); // 通过实例调用组件事件
    });
  },
  // 联系商家
  link_super_phone(){
    wx.makePhoneCall({
      phoneNumber: this.data.sao_super.phone
    })
  },
  // 中心提示窗
  hezuo_showToast(){
    this.judge_coop('hezuo_show');
    let that = this;
    setTimeout(function () {
      that.setData({
        is_hezuo_showToast:false
      });
    }, 2000)
  },
  // 显示合作流程弹窗
  show_hz_step(){
    this.setData({
      isShowHzStep:true
    });
    this.judge_coop();
  },
  // 申请合作
  AddsuperOK(){
    let that = this;
    if(that.data.sao_super.level == 4){
      app.AppHttp('api/Supplier/getCoopCustomCount', {  //免费版限制客户
        supplier_id:that.data.id
      }, function (res) {
        console.log(JSON.stringify(res.data));
        if(res.data.supplier_identity==0 && res.data.custom_count>=10){
          wx.showModal({
            title: '提示',
            content: "该供应商已有"+res.data.custom_count+"个客户\n供应商版本限定\n客户总量最多10个",
            showCancel: false,
            confirmText:"我知道了",
            success: function (res) {}
          });
          return;
        }else{
          that.conf_AddsuperOk_perf(that.data.loginInfo.id);
        };
      });
    }else{
      that.conf_AddsuperOk_perf(that.data.loginInfo.id);
    };
  },
  // 执行添加供应商接口
  conf_AddsuperOk_perf:function(client_id){
    var that = this;
    var message_type;
    if (that.data.sao_super.level == 1) {  //合作供应商端
      message_type = 'add_info';
    } else if (that.data.sao_super.level == 4) { //合作批发端
      message_type = 'pf_add_info';
    };
    // 添加供应商接口
    wx.request({
      url: app.globalData.url + 'api/Client/AddSupplier',
      method: "POST",
      data: {
        supplier_id: that.data.id,
        openid: app.globalData.openid
      },
      success: function (res) {
        wx.showToast({
          title: "申请成功",
        }, 2000);
        that.judge_coop();
        mySuperShop.onPullDownRefresh();  //刷新本页数据
        // 向供应商发送申请通知           
        wx.request({
          url: app.globalData.url + 'api/Message1/add_info',
          method: 'GET',
          data: {
            client_id: client_id,
            supplier_id: that.data.id,
            type: 1,   //1为请求，2为同意
            message_type: message_type
          },
          success: function (res) {
            console.log(JSON.stringify(res.data));
            if (that.data.sao_super.is_auto_agree == 1) {
              wx.request({
                url: app.globalData.url + 'api/Message1/add_info',
                method: 'GET',
                data: {
                  client_id: client_id,
                  supplier_id:  that.data.id,
                  type: 2  //1为请求，2为同意
                },
                success: function (res) {             
                  console.log(JSON.stringify(res.data));                   
                },fail:function(){
                  console.log("shibai");
                }
              });
            }
          }
        });       
      }
    });
  },
  // 取消申请供应商
  conf_noapply(){
    let that = this;
    app.AppHttp('api/Client/del_cooper', {
      id: that.data.sao_super.copper_id
    }, function (res) {
      console.log(JSON.stringify(res.data));
      if(res.data.status==1){
        that.setData({
          isAddsuper:false,
          isShowHzStep:false
        });
        wx.showToast({
          title:'已取消申请'
        });
      };
    });
  },
  // 关闭合作窗
  closeCoopSuper(){
    this.setData({
      isAddsuper:false,
      isShowHzStep:false
    });
  },
  // 返回页面
  back_page:function(){
    wx.navigateBack({
      delta:1
    });
  },
  noneEnoughPeople(){
    return;
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    wx.hideShareMenu();//隐藏转发分享按钮
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload(){
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh(){
    mySuperShop.onPullDownRefresh();
    wx.stopPullDownRefresh();
  },
  onPageScroll(e){
    var scrollTop = parseInt(e.scrollTop); //滚动条距离顶部高度;
    var isGun = scrollTop >= z_scroH ? true : false;
    if (this.data.gun === isGun) {
      return false;
    };
    this.setData({
      gun: isGun
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage(res) {  
    return {
      title:this.data.super_info.company_name+'的线上商城，邀请您下单！',
      path: 'pages/shangpin/shangpin?id='+this.data.id+'&type='+'super',
      imageUrl:'http://www.xiaobangcai.com/upload/smallprogram/mall_card1.jpg'
    }; 
  }
})